package cn.wangzg.course0902.util;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.provider.MediaStore;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

import cn.wangzg.course0902.Music;

/**
 * Time: 2020/4/16
 * Author: wangzhiguo
 * Description: 功能描述
 */
public class MusicUtil {

    public static ArrayList<Music> getMusic(ContentResolver resolver) {
        ArrayList<Music> list = new ArrayList<>();
        Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.Media._ID,
                        MediaStore.Audio.Media.TITLE,            //歌名
                        MediaStore.Audio.Media.ALBUM_ID,    //专辑id
                        MediaStore.Audio.Media.ALBUM,        //专辑
                        MediaStore.Audio.Media.DURATION,   //时长
                        MediaStore.Audio.Media.ARTIST,         //歌手
                        MediaStore.Audio.Media.DATA             //歌曲路径
                },
                MediaStore.Audio.Media.DURATION + ">=10000", //时长>10s
                null, null);
        while (cursor.moveToNext()) {
            Music music = new Music();
            music.setSong_id(cursor.getString(0));
            music.setTitle(cursor.getString(1));
            music.setAlbum_id(cursor.getInt(2));
            music.setAlbum_title(cursor.getString(3));
            music.setFile_duration(cursor.getInt(4) / 1000);//毫秒
            music.setArtist_name(cursor.getString(5));
            music.setUrl(cursor.getString(6));
            music.setLocal(true);
            System.out.println(music);
            list.add(music);
        }
        cursor.close();
        return list;
    }
    //异步运行
    public static void mediaScan(final Context context, File file) {
        System.out.println(file.getAbsolutePath());
        ArrayList<String> fileList = new ArrayList<>();
        //遍历文件夹的所有文件
        File[] files = file.listFiles();
        for (File ff : files) {
            if (ff.getName().endsWith("mp3")) {
                fileList.add(ff.getAbsolutePath());
            }
        }
        int size = fileList.size();
        //将List转为String[]
        String[] array = (String[]) fileList.toArray(new String[size]);
        //启动扫描  异步
        MediaScannerConnection.scanFile(context,
                array, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                        //将扫描的音乐文件（uri对应）添加到MediaStore
                        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        scanIntent.setData(uri);
                        context.sendBroadcast(scanIntent);
                    }
                });
    }

    /**
     * 根据专辑ID获取专辑封面图
     * @param album_id 专辑ID
     * @return
     * 注意：有的歌曲里面没有携带图片，返回null即可
     */
    public static Bitmap getAlbumArt(ContentResolver resolver,int album_id) {
        String mUriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[]{"album_art"};
        Cursor cur = resolver.query(Uri.parse(mUriAlbums + "/" + Integer.toString(album_id)),
                projection, null, null, null);
        String album_art = null;
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        cur.close();
        Bitmap bm = null;
        if (album_art != null) {
            bm = BitmapFactory.decodeFile(album_art);
        }
        return bm;
    }

    /**
     * 格式化时长为：00：00 格式化
     * @param duration 毫秒数
     * @return
     */
    public static String timeFormat(int duration){
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss", Locale.CHINA);
        return sdf.format(duration*1000);
    }
}
